package com.xfcy.content.service.impl;

import com.xfcy.content.mapper.CourseCategoryMapper;
import com.xfcy.content.model.dto.CourseCategoryTreeDto;
import com.xfcy.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 晓风残月Lx
 * @date 2023/6/11 16:21
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    /**
     * 课程分类树形查询
     * @param id
     * @return
     */
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        // 调用mapper进行查询出分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        // 找到每个节点的子节点，然后封装成List<CourseCategoryTreeDto>
        // 先将list转为map， key是节点的id， value就是CourseCategoryTreeDto对象   filter(item -> !id.equals(item.getId()))排除根节点
        Map<String, CourseCategoryTreeDto> map = courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        // 定义一个List作为最终返回的List
        List<CourseCategoryTreeDto> categoryTreeDtoList = new ArrayList<>();

        // 从头遍历List<CourseCategoryTreeDto>，一边遍历一遍找子节点的childrenTreeNodes
        courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).forEach(item -> {
            if (item.getParentid().equals(id)) {
                categoryTreeDtoList.add(item);
            }

            // 找到该节点的父节点,如果父节点不为空才执行
            CourseCategoryTreeDto courseCategoryParent = map.get(item.getParentid());
            if (courseCategoryParent != null) {
                if (courseCategoryParent.getChildrenTreeNodes() == null) {
                    // 如果该父节点的ChildrenTreeNodes属性为空要new一个集合，因为要向该集合中放它的子节点
                    courseCategoryParent.setChildrenTreeNodes(new ArrayList<>());
                }
                // 找到每个节点的子节点放在父节点的childrenTreeNodes中
                courseCategoryParent.getChildrenTreeNodes().add(item);
            }
        });
        return categoryTreeDtoList;
    }



}
